import 'dart:async';
import 'dart:io';

// import 'package:file_picker/file_picker.dart';
import 'package:flutter/services.dart';
import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:study_demo/base/BaseController.dart';
import 'package:study_demo/res/file.gen.dart';

class ReadPdfController extends BaseController {
  final pathPDF = "".obs;
//  final Completer<PDFViewController> pdfController =
//      Completer<PDFViewController>();

  @override
  void onInit() {
    super.onInit();

    requestPermission(Permission.storage, () {
      fromAsset(FileRes.demo, 'demo.pdf').then((f) {
        pathPDF.value = f.path;
      });
    });
  }

  Future<File> fromAsset(String asset, String filename) async {
    // To open from assets, you can copy them to the app storage folder, and the access them "locally"
    Completer<File> completer = Completer();

    try {
      var dir = await getApplicationDocumentsDirectory();
      File file = File("${dir.path}/$filename");
      var data = await rootBundle.load(asset);
      var bytes = data.buffer.asUint8List();
      await file.writeAsBytes(bytes, flush: true);
      completer.complete(file);
    } catch (e) {
      throw Exception('Error parsing asset file!');
    }
    return completer.future;
  }

  openDirectory() async {
    // FilePickerResult? result =
    //     await FilePicker.platform.pickFiles(type: FileType.any);
    // String path = result!.files.single.path!;
    // if (!path.endsWith('.pdf')) {
    //   toast('你选择的是非pdf文件,请重新选择');
    //   return;
    // }
    // pathPDF.value = path;
  }
}
